package sdk

import (
	"context"
	firebase "firebase.google.com/go"
	"firebase.google.com/go/messaging"
	"fmt"
	"gim-server/utils"
	"google.golang.org/api/option"
)

func GetFCM(ctx context.Context, key string) (*firebase.App, error) {
	opts := []option.ClientOption{option.WithCredentialsJSON(utils.StringToBytes(key))}
	return firebase.NewApp(ctx, nil, opts...)
}

func PushOneDevice(ctx context.Context, firebaseAuthKey string, deviceToken string, title string, body string) error {
	if firebaseAuthKey == "" {
		return nil
	}
	if deviceToken == "" {
		return nil
	}
	if title == "" {
		return nil
	}
	fcm, err := GetFCM(ctx, firebaseAuthKey)
	if err != nil {
		return err
	}
	fcmCli, err := fcm.Messaging(ctx)
	if err != nil {
		return err
	}
	response, err := fcmCli.Send(context.Background(), &messaging.Message{
		Notification: &messaging.Notification{
			Title: title,
			Body:  body,
		},
		Token: deviceToken, // it's a single device token
	})
	if err != nil {
		return err
	}
	fmt.Printf("PushOneDeviceResp => %+v\n", response)
	return nil
}

func PushMultiDevice(ctx context.Context, firebaseAuthKey string, deviceTokens []string, title string, body string) error {
	if firebaseAuthKey == "" {
		return nil
	}
	if len(deviceTokens) == 0 {
		return nil
	}
	if title == "" {
		return nil
	}
	fcm, err := GetFCM(ctx, firebaseAuthKey)
	if err != nil {
		return err
	}
	fcmCli, err := fcm.Messaging(ctx)
	if err != nil {
		return err
	}
	response, err := fcmCli.SendMulticast(context.Background(), &messaging.MulticastMessage{
		Notification: &messaging.Notification{
			Title: title,
			Body:  body,
		},
		Tokens: deviceTokens,
	})
	if err != nil {
		return err
	}
	fmt.Printf("PushMultiDeviceResp: SuccessCount => %+v, FailureCount => %+v\n", response.SuccessCount, response.FailureCount)
	return nil
}
